<template>
  <div class="overview">
    <!-- <div class="top">
                                    <div class="button-group">
                                      <button @click="changeLongitude(-5)">
                                        <BackwardOutlined style="font-size: 25px;" />
                                      </button>
                                      <button @click="changeLongitude(-1)">
                                        <CaretLeftOutlined style="font-size: 25px;" />
                                      </button>
                                      <a-select>
                                        <a-select-option :value="item.value" v-for="item in typeOptions" :key="item.label">{{
                                          item.value
                                          }}</a-select-option>
                                      </a-select>
                                    </div>
                                    <div class="longitude-display" id="longitude-display">{{ longitude }}</div>
                                    <div class="button-group">
                                      <button @click="changeLongitude(1)">
                                        <CaretRightOutlined style="font-size: 25px;" />
                                      </button>
                                      <button @click="changeLongitude(5)">
                                        <ForwardOutlined style="font-size: 25px;" />
                                      </button>
                                    </div>
                                  </div> -->
    <div class="bottom" v-if="flag">
      <a-table :columns="columns" :loading="loadings" :data-source="data" :pagination="false" :customRow="customRow">
        <!-- <template #_status="{ text, record }">
                                      <a style="color: #fff" @click="handleClick(record)">{{ text }}</a>
                                    </template> -->
        <template #title>List of Satellites at Geostationary orbit</template>
        <template #action="{ text, record, index}">
          {{ index+1 }}
        </template>
        <template #filterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }">
          <div style="padding: 8px">
            <a-input ref="searchInput" :placeholder="`Search ${column.dataIndex}`" :value="selectedKeys[0]"
              style="width: 188px; margin-bottom: 8px; display: block;background:#fff !important"
              @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])" :class="{'custom-placeholder': true}"
              @pressEnter="handleSearch(selectedKeys, confirm, column.dataIndex)" />
            <a-button type="primary" size="small" style="width: 90px; margin-right: 8px"
              @click="handleSearch(selectedKeys, confirm, column.dataIndex)">
              <template #icon>
                <SearchOutlined style="font-size: 14px; color: #fff" />
              </template>
              搜索
            </a-button>
            <a-button size="small" style="width: 90px" @click="handleReset(clearFilters)">
              重置
            </a-button>
          </div>
        </template>
      </a-table>
    </div>
    <div class="box" v-else>
      <button style="position: absolute;top: 40px;left:50px;width: 40px;height: 40px;" @click="changeLongitude()">
        <CaretLeftOutlined style="font-size: 25px;" />
      </button>
      <div class="left">
        <p>Satellite Name: {{ datas.satellite_name }}</p>
        <p>Status: {{ datas.status }}</p>
        <p>Position: {{ datas.detail_position }}</p>
        <p>NORAD: {{ datas.norad }}</p>
        <p>Cospar number: {{ datas.cospar_number }}</p>
        <p>Operator: {{ datas.operator }}</p>
        <p>Launch date: {{ datas.launch_date }}</p>
        <p>Launch site: {{ datas.launch_site }}</p>
        <p>Launch vehicle: {{datas.launch_vehicle }}</p>
        <p>Launch mass (kg): {{ datas['launch_mass_(kg)'] }}</p>
        <p>Dry mass (kg): {{ datas['dry_mass_(kg)'] }}</p>
        <p>Manufacturer: {{datas.manufacturer}}</p>
        <p>Model (bus): {{ datas['model_(bus)'] }}</p>
        <p>Orbit: {{ datas.orbit }}</p>
        <p>Expected lifetime: {{ datas.expected_lifetime }}</p>
      </div>
      <div class="right">
        <p>Call sign: {{ datas.call_sign }}</p>
        <p>Beacon(s): {{ datas['beacon(s)'] }}</p>
        <p>Details: {{ datas.details }}</p>
      </div>
      <div class="bottoms">
        <a-carousel arrows>
          <template #prevArrow>
            <div class="custom-slick-arrow" style="left: 10px; z-index: 1;color:#000 !important">
              <left-circle-outlined />
            </div>
          </template>
          <template #nextArrow>
            <div class="custom-slick-arrow" style="right: 10px;color:#000 !important">
              <right-circle-outlined />
            </div>
          </template>
          <div v-for="item, index in imgs" :key="index"  class="content_active"> <!-- 调整高度 -->
            <p style="margin-bottom: 16px; color: #fff; font-size: 20px">{{ item.name }}</p>
            <img style="height: 500px;object-fit: cover;" :src="'/api' + item.url" alt=""> <!-- 调整图片高度 -->
          </div>
        </a-carousel>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive, toRefs } from 'vue'
import { CaretLeftOutlined, BackwardOutlined, CaretRightOutlined, ForwardOutlined, LeftCircleOutlined, RightCircleOutlined } from '@ant-design/icons-vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
export default defineComponent({
  name: 'overview',
  components: {
    CaretLeftOutlined, BackwardOutlined, CaretRightOutlined, ForwardOutlined, LeftCircleOutlined,
    RightCircleOutlined,
  },

  setup() {
    // const baseImgUrl = 'http://123.125.194.157:18080/api'
    const baseImgUrl = 'http://192.168.14.164:8080/api'
    const loadings = ref(true)
    const router = useRouter();
    const typeOptions = ref([
      {
        value: 'w',
        label: 'M710a',
      },
      {
        value: 'e',
        label: 'M650',
      },
    ]);

    // 表格Launch_data排序
    const sortLaunch_data = (a, b) => {
      // 自定义日期解析函数  
      const parseDate = (dateStr) => {
        // 移除括号内的文本  
        const cleanDateStr = dateStr.replace(/\s*\(.*?\)\s*/g, '');
        // 解析日期字符串为 Date 对象  
        const [day, month, year] = cleanDateStr.split('-');
        const monthMap = {
          Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5,
          Jul: 6, Aug: 7, Sep: 8, Oct: 9, Nov: 10, Dec: 11
        };
        const monthIndex = monthMap[month];
        return new Date(year, monthIndex, day);
      };

      // 解析两个日期字符串为 Date 对象  
      const dateA = parseDate(a.launch_date);
      const dateB = parseDate(b.launch_date);

      // 比较两个 Date 对象  
      return dateA - dateB;
    }

    // 表格Cospar排序
    const sortCospar = (a, b) => {
      // 提取年份和序号（去除前导零）  
      const extractNumber = (cospar) => {
        const match = cospar.cospar_number.match(/^(\d{4})-(\d+)/);
        if (match) {
          const year = parseInt(match[1], 10);
          const sequence = parseInt(match[2].replace(/^0+/, ''), 10); // 去除序号前的前导零  
          return { year, sequence };
        }
        return { year: Infinity, sequence: Infinity }; // 如果没有匹配到，则返回一个很大的数，确保它排在最后  
      };

      const { year: yearA, sequence: sequenceA } = extractNumber(a);
      const { year: yearB, sequence: sequenceB } = extractNumber(b);

      // 先比较年份，如果年份相同再比较序号  
      if (yearA !== yearB) {
        return yearA - yearB;
      }
      return sequenceA - sequenceB;
    };
    let longitude = ref(0)
    function changeLongitude() {
      flag.value = true
    }
    function customRow(record, index) {
      return {
        onClick: () => handleClick(record, index)
      };
    }
    let datas = ref({})
    let flag = ref(true)
    let imgs = ref([])
    const handleClick: Function = (record) => {
      datas.value = record
      imgs.value = record.pics
      flag.value = false
      // router.push({ path: '/satellite/detail', query: record  });
    }

    const searchInput = ref();
    // 自定义筛选菜单START
    const state = reactive({
      searchText: '',
      searchedColumn: '',
    });
    const handleReset = clearFilters => {
      clearFilters();
      state.searchText = '';
    };
    const handleSearch = (selectedKeys, confirm, dataIndex) => {
      confirm();
      state.searchText = selectedKeys[0];
      state.searchedColumn = dataIndex;
    }
    let data = ref([
      // {
      //   _position: '1',
      //   _status: 'John Brown',
      //   age: 32,
      //   address: 'New York No. 1 Lake Park',
      // },
      // {
      //   _position: '2',
      //   name: 'Jim Green',
      //   age: 42,
      //   address: 'London No. 1 Lake Park',
      // },
      // {
      //   _position: '3',
      //   name: 'Joe Black',
      //   age: 32,
      //   address: 'Sidney No. 1 Lake Park',
      // },
      // {
      //   _position: '4',
      //   name: 'Jim Red',
      //   age: 32,
      //   address: 'London No. 2 Lake Park',
      // },
    ]);


    // 使用 axios 发起 GET 请求，获取卫星信息
    axios.get('/api/sat_info').then((res) => {
      // 检查响应数据中的数据长度是否大于 0
      if (res.data.data.result.data.length > 0) {
        // 如果数据长度大于 0，将数据赋值给 data 变量
        data.value = res.data.data.result.data
        // 将加载状态设置为 false，表示数据加载完成
        loadings.value = false
      }
      // 检查响应数据中的代码是否为 500 或 502
      else if (res.data.data.result.data.code == 500 || res.data.data.result.data.code == 502) {
        // 如果代码为 500 或 502，将加载状态设置为 false
        loadings.value = false
        // 将数据设置为空数组
        data.value == []
      }
      // 其他情况
      else {
        // 将加载状态设置为 true，表示数据正在加载
        loadings.value = true
      }
    })


    // 表格列头显示
    const columns = [
      {
        title: '',
        dataIndex: 'id',
        defaultSortOrder: 'descend',
        slots: { customRender: 'action' },
      },
      {
        title: 'Potition',
        dataIndex: 'position',
        align: 'center',
        // sortDirections: ['descend'],
        sorter: (a, b) => customSortPosition(a, b), // 使用自定义排序函数
      },
      {
        title: 'Status',
        align: 'center',
        dataIndex: 'status',
        defaultSortOrder: 'descend',
        // slots: {
        //   filterDropdown: 'filterDropdown',
        //   filterIcon: 'filterIcon',
        //   customRender: 'customRender',
        // },
        // onFilter: (value, record) => {
        //   console.log(record, record.value, record.name, 'record')
        //   return record.status.toString().toLowerCase().includes(value.toLowerCase())
        // },
        // // record.name.toString().toLowerCase().includes(value.toLowerCase()),
        // onFilterDropdownVisibleChange: visible => {
        //   if (visible) {
        //     setTimeout(() => {
        //       console.log(searchInput.value);
        //       searchInput.value.focus();
        //     }, 100);
        //   }
        // },
        filters: [
          { text: 'Active', value: 'active' },
          { text: 'Retired', value: 'retired' },
          { text: 'Deorbited', value: 'deorbited' },
          { text: 'Failed', value: 'failed' },
          { text: 'Planned', value: 'planned' },
          { text: 'Disabled', value: 'disabled' },
          { text: 'Moving', value: 'moving' },
          { text: 'Testing', value: 'testing' },
        ],
        filterMultiple: false,
        slots: { customRender: '_status' },
        onFilter: (value: string, record: TableDataType) => record.status.indexOf(value) === 0,
      },
      {
        align: 'center',
        title: 'Satellite Name',
        dataIndex: 'satellite_name',
        slots: {
          filterDropdown: 'filterDropdown',
          filterIcon: 'filterIcon',
          customRender: 'customRender',
        },
        onFilter: (value, record) => {
          console.log(record, record.value, record.name, 'record')
          return record.satellite_name.toString().toLowerCase().includes(value.toLowerCase())
        },
        // record.name.toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownVisibleChange: visible => {
          if (visible) {
            setTimeout(() => {
              console.log(searchInput.value);
              searchInput.value.focus();
            }, 100);
          }
        },
        filterMultiple: false,
        // onFilter: (value: string, record: TableDataType) => record.satelliteName.indexOf(value) === 0,
        sortDirections: ['descend', 'ascend'],
      },
      {
        align: 'center',
        title: 'Norad',
        dataIndex: 'norad',
        sorter: (a, b) => a.norad - b.norad,
        filterMultiple: false,
        // onFilter: (value: string, record: TableDataType) => record.norad.indexOf(value) === 0,
        sortDirections: ['descend', 'ascend'],
      },
      {
        align: 'center',
        title: 'Cospar',
        dataIndex: 'cospar_number',
        filterMultiple: false,
        sorter: sortCospar,
        sortDirections: ['descend', 'ascend'],
      },
      {
        title: 'Satellite Model',
        align: 'center',
        dataIndex: 'model_(bus)',
        slots: {
          filterDropdown: 'filterDropdown',
          filterIcon: 'filterIcon',
          customRender: 'customRender',
        },
        onFilter: (value, record) => {
          console.log(record, record.value, record.name, 'record')
          return record['model_(bus)'].toString().toLowerCase().includes(value.toLowerCase())
        },
        // record.name.toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownVisibleChange: visible => {
          if (visible) {
            setTimeout(() => {
              console.log(searchInput.value);
              searchInput.value.focus();
            }, 100);
          }
        },
        filterMultiple: false,
        // onFilter: (value: string, record: TableDataType) => record.satelliteModel.indexOf(value) === 0,
        sortDirections: ['descend', 'ascend'],
      },
      {
        title: 'Operator',
        align: 'center',
        dataIndex: 'operator',
        filterMultiple: false,
        // onFilter: (value: string, record: TableDataType) => record.operator.indexOf(value) === 0,
        sortDirections: ['descend', 'ascend'],
        slots: {
          filterDropdown: 'filterDropdown',
          filterIcon: 'filterIcon',
          customRender: 'customRender',
        },
        onFilter: (value, record) => {
          console.log(record, record.value, record.name, 'record')
          return record.operator.toString().toLowerCase().includes(value.toLowerCase())
        },
        // record.name.toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownVisibleChange: visible => {
          if (visible) {
            setTimeout(() => {
              console.log(searchInput.value);
              searchInput.value.focus();
            }, 100);
          }
        },
      },
      {
        title: 'Launch site',
        align: 'center',
        dataIndex: 'launch_site',
        filterMultiple: false,
        // onFilter: (value: string, record: TableDataType) => record.launchsite.indexOf(value) === 0,
        sortDirections: ['descend', 'ascend'],
        slots: {
          filterDropdown: 'filterDropdown',
          filterIcon: 'filterIcon',
          customRender: 'customRender',
        },
        onFilter: (value, record) => {
          console.log(record, record.value, record.name, 'record')
          return record.launch_site.toString().toLowerCase().includes(value.toLowerCase())
        },
        // record.name.toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownVisibleChange: visible => {
          if (visible) {
            setTimeout(() => {
              console.log(searchInput.value);
              searchInput.value.focus();
            }, 100);
          }
        },
      },
      {
        title: 'Launch mass',
        align: 'center',
        dataIndex: 'launch_mass_(kg)',
        sorter: (a, b) => a['launch_mass_(kg)'] - b['launch_mass_(kg)'],
        filterMultiple: false,
        // onFilter: (value: string, record: TableDataType) => record.launchmass.indexOf(value) === 0,
        sortDirections: ['descend', 'ascend'],
      },
      {
        title: 'Launch date',
        align: 'center',
        dataIndex: 'launch_date',
        sorter: sortLaunch_data,
        filterMultiple: false,
        // onFilter: (value: string, record: TableDataType) => record.launchdate.indexOf(value) === 0,
        sortDirections: ['descend', 'ascend'],
      },
      {
        title: 'Comments',
        align: 'center',
        dataIndex: 'details',
        slots: {
          filterDropdown: 'filterDropdown',
          filterIcon: 'filterIcon',
          customRender: 'customRender',
        },
        onFilter: (value, record) => {
          console.log(record, record.value, record.name, 'record')
          return record.details.toString().toLowerCase().includes(value.toLowerCase())
        },
        // record.name.toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownVisibleChange: visible => {
          if (visible) {
            setTimeout(() => {
              console.log(searchInput.value);
              searchInput.value.focus();
            }, 100);
          }
        },
        filterMultiple: false,
        // onFilter: (value: string, record: TableDataType) => record.comments.indexOf(value) === 0,
        sortDirections: ['descend', 'ascend'],
      },
    ];
    // 位置position排序
    const customSortPosition = (a, b) => {
      const getPositionValue = (pos) => {
        const isE = pos.endsWith('E');
        const isW = pos.endsWith('W');
        const numberPart = parseInt(pos.slice(0, -1), 10);

        if (isE) {
          return { value: numberPart, type: 'E' }; // E按照数字排序
        } else if (isW) {
          return { value: 180 - numberPart, type: 'W' }; // W倒序处理
        }
        return { value: 0, type: '' };
      };

      const aValue = getPositionValue(a.position);
      const bValue = getPositionValue(b.position);

      if (aValue.type === bValue.type) {
        return aValue.value - bValue.value; // 同类项按值排序
      }
      return aValue.type === 'E' ? -1 : 1; // E在W前
    };


    // 倒序排序
    // const sortedDesc = data.value.slice().sort((a, b) => {
    //   const getPositionValue = (pos) => {
    //     const isE = pos.endsWith('E');
    //     const isW = pos.endsWith('W');
    //     const numberPart = parseInt(pos.slice(0, -1), 10);

    //     if (isW) {
    //       return { value: numberPart, type: 'W' }; // W按照数字排序
    //     } else if (isE) {
    //       return { value: 180 - numberPart, type: 'E' }; // E倒序处理
    //     }
    //     return { value: 0, type: '' };
    //   };

    //   const aValue = getPositionValue(a.position);
    //   const bValue = getPositionValue(b.position);

    //   if (aValue.type === bValue.type) {
    //     return aValue.value - bValue.value; // 同类项按值排序
    //   }
    //   return aValue.type === 'W' ? -1 : 1; // W在E前
    // });




    return {
      changeLongitude, longitude, typeOptions, columns, data, handleClick, datas, flag, imgs, customRow, loadings, baseImgUrl, searchInput, ...toRefs(state), handleReset,
      handleSearch,

    }
  },
})
</script>
<style scoped lang=less>
.overview {
  width: 100%;
  height: 100%;
  padding-top: 80px;
  padding-left: 30px;
  padding-right: 30px;
  box-sizing: border-box;

  .top {
    width: 100%;
    height: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 10px;

    ::v-deep .ant-select-selector {
      color: #fff !important;
    }

    .longitude-display {
      margin: 0 20px;
      font-size: 24px;
      color: #fff;
    }

    .button-group {
      display: flex;
      align-items: center;
    }

    button {
      margin: 5px;
      padding: 10px;
      font-size: 16px;
      cursor: pointer;
      border: none;
      border-radius: 5px;
      color: white;
      transition: background-color 0.3s ease;
    }

    button:hover {
      background-color: #ccc;
    }
  }

  .bottom {
    width: 100%;
    height: calc(100% - 100px);
    // background: pink;
    margin-top: 10px;

    //表格头部样式
    ::v-deep .ant-table-title {
      text-align: center !important;
      height: 30px;
      padding: 0;
      line-height: 30px;
      font-size: 15px;
    }

    ::v-deep .ant-table-thead>tr>th {
      padding: 5px 0;
      border: 0.5px solid #ccc !important;
      box-sizing: border-box;
    }

    ::v-deep .ant-table-tbody>tr>td {
      border: 0.5px solid #ccc;
      box-sizing: border-box;
    }

    ::v-deep .ant-table-thead>tr>th .anticon-filter {
      // right: null;
      // position: relative;
      // height: 18px;
      // text-align: center;
    }

    ::v-deep .ant-table-thead>tr>th.ant-table-column-has-actions.ant-table-column-has-filters {
      // padding-right: 0 !important;
    }
  }

  ::v-deep {

    .ant-table-thead>tr.ant-table-row-hover:not(.ant-table-expanded-row):not(.ant-table-row-selected)>td,
    .ant-table-tbody>tr.ant-table-row-hover:not(.ant-table-expanded-row):not(.ant-table-row-selected)>td,
    .ant-table-thead>tr:hover:not(.ant-table-expanded-row):not(.ant-table-row-selected)>td,
    .ant-table-tbody>tr:hover:not(.ant-table-expanded-row):not(.ant-table-row-selected)>td {
      color: #000;

      a {
        color: blue !important;
      }
    }
  }
}

.box {
  width: 100%;
  height: 100%;
  color: #fff;

  .left {
    width: 50%;
    float: left;
    padding: 20px;
    box-sizing: border-box;

    p {
      margin-bottom: 5px;
    }
  }

  .right {
    width: 50%;
    float: left;
    padding: 20px;
    box-sizing: border-box;
  }

  .bottoms {
    width: 100%;
    float: left;
    padding: 20px;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
  }

}

.ant-carousel :deep(.slick-slide) {
  text-align: center;
  height: 550px;
  // line-height: 550px;
  // background: #364d79;
  overflow: hidden;
}

::v-deep .ant-carousel {
  width: 50%;
}

.ant-carousel :deep(.slick-arrow.custom-slick-arrow) {
  width: 25px;
  height: 25px;
  font-size: 25px;
  color: #fff;
  background-color: rgba(31, 45, 61, 0.11);
  opacity: 0.3;
}

.ant-carousel :deep(.custom-slick-arrow:before) {
  display: none;
}

.ant-carousel :deep(.custom-slick-arrow:hover) {
  opacity: 0.5;
}

.ant-carousel :deep(.slick-slide h3) {
  color: #fff;
}

::v-deep .slick-dots-bottom {
  display: none !important;
}

::v-deep .slick-initialized {
  height: 498px !important;
  width: 500px;
}

::v-deep .slick-list {
  height: 100% !important;
}

::v-deep .custom-slick-arrow {
  color: #000 !important;
  opacity: 1;
}

button:hover {
  background-color: #ccc;
}

::v-deep .custom-placeholder {
  color: #000 !important;
}

</style>